/**
 * 
 */
package edu.cmu.cs.webapp.ioms.actions.order;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.OrderDAOImpl;
import edu.cmu.cs.webapp.ioms.models.PurchaseOrder;
import edu.cmu.cs.webapp.ioms.ui.wizards.order.OrderWizard;
import edu.cmu.cs.webapp.ioms.views.CustomersListView;
import edu.cmu.cs.webapp.ioms.views.InventoryView;
import edu.cmu.cs.webapp.ioms.views.OrdersListView;

/**
 * @author Christian
 * 
 */
public class NewOrderViewAction implements IViewActionDelegate {
	private OrdersListView _view;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
	 */
	@Override
	public void init(IViewPart view) {
		this._view = (OrdersListView) view;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(IAction action) {
		OrderWizard wizard = new OrderWizard(false, null);
		wizard.setWindowTitle("Add Order");
		WizardDialog dialog = new WizardDialog(_view.getViewSite().getShell(),
				wizard);
		dialog.setBlockOnOpen(true);
		dialog.open();

		int returnCode = dialog.getReturnCode();

		if (returnCode == org.eclipse.jface.window.Window.OK) {
			// create new order
			PurchaseOrder order = wizard.getModel();
			try {
				new OrderDAOImpl().addOrderItems(order);
			} catch (DataAccessException e) {
			}

			CustomersListView
					.getCustomersListViewPart(this._view.getViewSite())
					.refreshCustomersView();
			InventoryView.getInventoryView(this._view.getViewSite())
					.refreshInventoryView();
			this._view.refreshOrdersView();

		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action
	 * .IAction, org.eclipse.jface.viewers.ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		// TODO Auto-generated method stub
	}

}
